#! /usr/bin/python
# -*- coding: utf-8 -*-

import urllib

paperLinksCount = 5
onePagePapersCount = 15

def getPaperNavbar(request):
    paperNavbar = {}
    offset = request.get('offset')
    if not offset:
        paperNavbar['offset'] = 0
    else:
        try:
            paperNavbar['offset'] = int(offset)
        except ValueError:
            paperNavbar['offset'] = 0
    paperNavbar['limit'] = onePagePapersCount
    
    if paperNavbar.get('offset'):
        prevPageOffset = paperNavbar['offset'] - onePagePapersCount
        if prevPageOffset < 0:
            prevPageOffset = 0
        paperNavbar['prevLink'] = getUrlPathQueryExceptParam(request, 'offset', prevPageOffset)
    nextPageOffset = paperNavbar['offset'] + onePagePapersCount
    paperNavbar['nextLink'] = getUrlPathQueryExceptParam(request, 'offset', nextPageOffset)
    
    paperNavbar['pageLinks'] = []
    firstLinkOffset = paperNavbar['offset'] - (paperLinksCount / 2) * onePagePapersCount
    if firstLinkOffset < 0:
        firstLinkOffset = 0
    i = 0
    while i < paperLinksCount:
        offset = firstLinkOffset + onePagePapersCount * i
        text = str(offset / onePagePapersCount + 1)
        href = getUrlPathQueryExceptParam(request, 'offset', offset)
        paperNavbar['pageLinks'].append({'href':href, 'text':text, 'offset':offset})
        i += 1
    return paperNavbar

def getUrlPathQueryExceptParam(request, exceptParamName, exceptParamValue):
    path = request.path
    args = request.arguments()
    i = 0
    while i < len(args):
        if args[i] == exceptParamName:
            del args[i]
            break
        i += 1
    path += '?' + urllib.urlencode({exceptParamName:exceptParamValue})
    for name in args:
        path += '&' + name + '=' + request.get(name)
    return path
